package com.readboottest.ipagent;


import com.readboottest.entity.IpAgent;
import com.readboottest.enums.WebsiteEnum;
import com.readboottest.util.HttpUtilS;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import static com.readboottest.constant.NovelConstant.CODE_UTF_8;


/**
 * @author zhanghuiyong
 * @创建时间 2019年06月12日
 * @描述: 动态ip获取实现
 **/

public class IpAgentService {

    public static List<IpAgent> getAgentIps() {
        List<IpAgent> agentIps = new ArrayList<>();
        String url = WebsiteEnum.WEBSITE_DATE5U.getSearchUrl();
        String searchResult = HttpUtilS.doGet(url, CODE_UTF_8);
        //解析文档
        Document doc = Jsoup.parse(searchResult);

        //根据 l2 class 获取域名信息
        Elements ipElementsByl2 = doc.getElementsByClass("l2");
        for (Element ipElement : ipElementsByl2) {
            Elements ipInfoBySpan = ipElement.getElementsByTag("span");
            IpAgent ipAgent = getIpAgent(ipInfoBySpan);
            agentIps.add(ipAgent);
        }
        return agentIps;
    }

    /**
     * 获取ipAgent
     *
     * @param ipInfoBySpan
     * @return
     */
    private static IpAgent getIpAgent(Elements ipInfoBySpan) {
        IpAgent ipAgent = new IpAgent();
        //ip
        ipAgent.setIp(ipInfoBySpan.get(0).text());
        //端口
        ipAgent.setPort(Integer.valueOf(ipInfoBySpan.get(1).text()));
        //匿名程度
        ipAgent.setAnonymity(ipInfoBySpan.get(2).text());
        //类型
        ipAgent.setType(ipInfoBySpan.get(3).text());
        //国家
        ipAgent.setCountry(ipInfoBySpan.get(4).text());
        //地区
        ipAgent.setRegion(ipInfoBySpan.get(5).text());
        //运营商
        ipAgent.setOperators(ipInfoBySpan.get(6).text());
        //网速
        ipAgent.setSpeed(ipInfoBySpan.get(7).text());
        //最后更新时间
        ipAgent.setLastTime(ipInfoBySpan.get(7).text());
        return ipAgent;
    }
}
